package com.dev;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class App {
    private static final String NUM = "0123456789";
    private static final String LOWERCASE = "abcdefghijklmnopqrstuvwxyz";
    private static final String UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String SPECIALCHAR = "!@#$%^&*";

    public static void main(String[] args) {
        JFrame frame = new JFrame("密码生成器");
        frame.setContentPane(new App().jPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setResizable(false);
        frame.setVisible(true);
    }

    private JPanel jPanel;
    private JCheckBox checkBox1;
    private JCheckBox checkBox2;
    private JCheckBox checkBox3;
    private JCheckBox checkBox4;
    private JSpinner spinner1;
    private JTextArea textArea1;
    private JButton button;

    public App() {
        super();
        init();
    }

    private void init() {
        checkBox1.setSelected(true);
        checkBox2.setSelected(true);
        checkBox3.setSelected(true);
        spinner1.setModel(new SpinnerNumberModel(16, 1, 100, 1));
        textArea1.setBorder(LineBorder.createGrayLineBorder());
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    genPwd();
                } catch (RuntimeException re) {
                    JOptionPane.showMessageDialog(null, re.getMessage(), "提示",JOptionPane.INFORMATION_MESSAGE);
                }

            }
        });
    }


    public void genPwd() {
        boolean hasNum = checkBox1.isSelected();
        boolean hasLowerCase = checkBox2.isSelected();
        boolean hasUpperCase = checkBox3.isSelected();
        boolean hasSpecialChar = checkBox4.isSelected();
        StringBuilder allowString = new StringBuilder();
        if(hasNum) {
            allowString.append(NUM);
        }
        if(hasLowerCase) {
            allowString.append(LOWERCASE);
        }
        if(hasUpperCase) {
            allowString.append(UPPERCASE);
        }
        if(hasSpecialChar) {
            allowString.append(SPECIALCHAR);
        }
        if(allowString.length() == 0) {
            throw new RuntimeException("请选择生成密码的字符");
        }
        int pwdLen = (Integer)spinner1.getValue();
        int allowStrLen = allowString.length();
        Random random = new Random();
        StringBuilder pwd = new StringBuilder();
        for (int i = 0; i < pwdLen; ++i) {
            pwd.append(allowString.charAt(random.nextInt(allowStrLen)));
        }
        textArea1.setText(pwd.toString());
    }
}
